<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>扫码报工-会员中心 - 工厂报工系统</title>
{include file="common/header" /}

<div class="max-w-4xl mx-auto">
    <div class="bg-white rounded-lg shadow-lg p-6">
        <div class="text-center mb-8">
            <h3 class="text-2xl font-bold text-gray-800 mb-2">
                <i class="fa fa-qrcode text-primary mr-2"></i> 扫码报工
            </h3>
            <p class="text-gray-600">扫描任务二维码或手动输入任务ID进行报工</p>
        </div>

        <!-- 扫码方式选择 -->
        <div class="grid grid-cols-2 gap-4 mb-8">
            <div class="scan-method active border-2 border-primary bg-primary text-white rounded-lg p-6 text-center cursor-pointer transition-all" data-method="camera">
                <i class="fa fa-camera text-3xl mb-3"></i>
                <div class="font-semibold">摄像头扫码</div>
            </div>
            <div class="scan-method border-2 border-gray-200 rounded-lg p-6 text-center cursor-pointer transition-all hover:border-primary" data-method="manual">
                <i class="fa fa-keyboard-o text-3xl mb-3"></i>
                <div class="font-semibold">手动输入</div>
            </div>
        </div>

        <!-- 摄像头扫码 -->
        <div id="camera-method" class="scan-content">
            <div class="text-center">
                <video id="video" class="max-w-full rounded-lg border-2 border-gray-300 mx-auto mb-4"></video>
                <div class="space-x-4">
                    <button class="px-6 py-2 bg-primary text-white rounded-lg hover:bg-blue-700 transition-colors" id="start-camera">
                        <i class="fa fa-play mr-2"></i> 开启摄像头
                    </button>
                    <button class="px-6 py-2 bg-red-500 text-white rounded-lg hover:bg-red-700 transition-colors hidden" id="stop-camera">
                        <i class="fa fa-stop mr-2"></i> 关闭摄像头
                    </button>
                </div>
            </div>
        </div>

        <!-- 手动输入 -->
        <div id="manual-method" class="scan-content hidden">
            <div class="max-w-md mx-auto">
                <div class="mb-4">
                    <label for="task-id" class="block text-sm font-medium text-gray-700 mb-2">任务ID：</label>
                    <input type="text" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary" id="task-id" placeholder="请输入任务ID">
                </div>
                <button class="w-full px-6 py-2 bg-primary text-white rounded-lg hover:bg-blue-700 transition-colors" id="submit-task-id">
                    <i class="fa fa-search mr-2"></i> 查询任务
                </button>
            </div>
        </div>

        <!-- 扫码结果 -->
        <div id="scan-result" class="hidden">
            <!-- 结果内容将通过JavaScript动态填充 -->
        </div>

        <!-- 直接显示任务信息（来自URL参数） -->
        {if isset($task)}
        <div class="bg-white border border-gray-200 rounded-lg p-6 mt-6">
            <h4 class="text-lg font-semibold text-gray-800 mb-4">任务信息</h4>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                <div class="flex justify-between">
                    <span class="font-medium text-gray-700">分配ID：</span>
                    <span class="text-gray-900">{$task.id|default='-'}</span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-700">订单号：</span>
                    <span class="text-gray-900">{$task.order_no|default='-'}</span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-700">产品：</span>
                    <span class="text-gray-900">{$task.product_name|default='-'} - {$task.model_name|default='-'}</span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-700">工序：</span>
                    <span class="text-gray-900">{$task.process_name|default='-'}</span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-700">待报数量：</span>
                    <span class="text-gray-900 font-semibold text-primary">{$task.remaining_quantity|default=0}</span>
                </div>
            </div>
            <div class="text-center">
                <button class="px-6 py-3 bg-green-500 text-white rounded-lg hover:bg-green-700 transition-colors" onclick="submitReport({$task.id}, {$task.remaining_quantity})"
                    <i class="fa fa-check mr-2"></i> 确认报工
                </button>
            </div>
        </div>
        {/if}
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
$(function() {
    var currentMethod = 'camera';
    var stream = null;
    
    // 扫码方式切换
    $('.scan-method').click(function() {
        var method = $(this).data('method');
        switchScanMethod(method);
    });
    
    // 开启摄像头
    $('#start-camera').click(function() {
        startCamera();
    });
    
    // 关闭摄像头
    $('#stop-camera').click(function() {
        stopCamera();
    });
    
    // 提交任务ID
    $('#submit-task-id').click(function() {
        var taskId = $('#task-id').val();
        if (taskId) {
            scanQRCode(taskId);
        } else {
            showAlert('请输入任务ID', 'warning');
        }
    });
    
    // 切换扫码方式
    function switchScanMethod(method) {
        currentMethod = method;
        $('.scan-method').removeClass('active border-primary bg-primary text-white').addClass('border-gray-200');
        $('.scan-method[data-method="' + method + '"]').removeClass('border-gray-200').addClass('active border-primary bg-primary text-white');
        
        $('.scan-content').addClass('hidden');
        if (method === 'camera') {
            $('#camera-method').removeClass('hidden');
        } else {
            $('#manual-method').removeClass('hidden');
            stopCamera();
        }
    }
    
    // 开启摄像头
    function startCamera() {
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } })
                .then(function(mediaStream) {
                    stream = mediaStream;
                    var video = document.getElementById('video');
                    video.srcObject = mediaStream;
                    $('#start-camera').addClass('hidden');
                    $('#stop-camera').removeClass('hidden');
                    
                    // 开始扫码
                    scanQRCode();
                })
                .catch(function(error) {
                    showAlert('无法访问摄像头：' + error.message, 'danger');
                });
        } else {
            showAlert('您的浏览器不支持摄像头功能', 'warning');
        }
    }
    
    // 关闭摄像头
    function stopCamera() {
        if (stream) {
            stream.getTracks().forEach(function(track) {
                track.stop();
            });
            stream = null;
        }
        $('#start-camera').removeClass('hidden');
        $('#stop-camera').addClass('hidden');
    }
    
    // 扫码功能
    function scanQRCode(content) {
        if (content) {
            // 手动输入的任务ID
            processQRCode(content);
        } else {
            // 摄像头扫码
            var canvas = document.createElement('canvas');
            var video = document.getElementById('video');
            var context = canvas.getContext('2d');
            
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            context.drawImage(video, 0, 0, canvas.width, canvas.height);
            
            // 这里应该使用二维码识别库
            // 由于没有实际的二维码识别库，这里只是示例
            setTimeout(scanQRCode, 100);
        }
    }
    
    // 处理二维码数据
    function processQRCode(qrCode) {
        $.post('{:url("worker/scan")}', {qr_code: qrCode}, function(data) {
            if (data.code === 1) {
                showTaskInfo(data.data);
            } else {
                showAlert(data.msg, 'danger');
            }
        });
    }
    
    // 显示任务信息
    function showTaskInfo(task) {
    var html = `
        <div class="bg-white border border-gray-200 rounded-lg p-6 mt-6">
            <h4 class="text-lg font-semibold text-gray-800 mb-4">任务信息</h4>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                <div class="flex justify-between">
                    <span class="font-medium text-gray-700">订单号：</span>
                    <span class="text-gray-900">${task.order_no || '-'}</span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-700">产品：</span>
                    <span class="text-gray-900">${task.product_name || '-'} - ${task.model_name || '-'}</span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-700">工序：</span>
                    <span class="text-gray-900">${task.process_name || '-'}</span>
                </div>
                <div class="flex justify-between">
                    <span class="font-medium text-gray-700">待报数量：</span>
                    <span class="text-gray-900 font-semibold text-primary">${task.remaining_quantity}</span>
                </div>
            </div>
            <div class="text-center">
                <button class="px-6 py-3 bg-green-500 text-white rounded-lg hover:bg-green-700 transition-colors" id="submit-report">
                    <i class="fa fa-check mr-2"></i> 确认报工
                </button>
            </div>
        </div>
    `;
    $('#scan-result').removeClass('hidden').html(html);
        
        // 绑定确认报工事件
        $('#submit-report').click(function() {
            submitReport(task.id, task.remaining_quantity);
        });
    }
    
    // 提交报工
    function submitReport(allocationId, quantity) {
        $.post('{:url("worker/submit")}', {
            allocation_id: allocationId,
            quantity: quantity
        }, function(data) {
            if (data.code === 1) {
                showAlert('报工成功！', 'success');
                $('#scan-result').addClass('hidden');
            } else {
                showAlert('报工失败：' + data.msg, 'danger');
            }
        });
    }
    
    // 全局函数，供HTML直接调用
    window.submitReport = submitReport;
    
    // 显示提示信息
    function showAlert(message, type) {
        var alertClass = type === 'success' ? 'bg-green-100 text-green-800' : 
                        type === 'warning' ? 'bg-yellow-100 text-yellow-800' : 
                        'bg-red-100 text-red-800';
        
        var alertHtml = `
            <div class="p-4 rounded-lg ${alertClass} mb-4 flex items-center justify-between">
                <span>${message}</span>
                <button type="button" class="text-gray-500 hover:text-gray-700" onclick="this.parentElement.remove()">
                    <i class="fa fa-times"></i>
                </button>
            </div>
        `;
        $('.bg-white.rounded-lg.shadow-lg.p-6').prepend(alertHtml);
        
        // 3秒后自动消失
        setTimeout(function() {
            $('.p-4.rounded-lg').fadeOut();
        }, 3000);
    }
    
    // 任务信息已通过HTML直接显示，无需JavaScript处理
});
</script>

{include file="common/footer" /} 